package tv.huan.media.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tv.huan.common.core.text.Convert;
import tv.huan.common.utils.DateUtils;
import tv.huan.media.domain.Album;
import tv.huan.media.domain.ItemAlbumOperateLog;
import tv.huan.media.domain.Settlement;
import tv.huan.media.mapper.AlbumMapper;
import tv.huan.media.mapper.ItemAlbumMapper;
import tv.huan.media.domain.ItemAlbum;
import tv.huan.media.mapper.ItemAlbumOperateLogMapper;
import tv.huan.media.mapper.ItemMapper;
import tv.huan.media.rabbit.RabbitConstant;
import tv.huan.media.service.IItemAlbumService;
import tv.huan.media.util.MailInfoUtil;
import tv.huan.system.domain.SysUser;

/**
 * 项目专辑关系Service业务层处理
 *
 * @author admin
 * @date 2019-10-12
 */
@Service
public class ItemAlbumServiceImpl implements IItemAlbumService {
    @Autowired
    private ItemAlbumMapper itemAlbumMapper;

    @Autowired
    private ItemAlbumOperateLogMapper itemAlbumOperateLogMapper;

    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private AmqpTemplate rabbitmqTemplate;

    /**
     * 查询项目专辑关系
     *
     * @param id 项目专辑关系ID
     * @return 项目专辑关系
     */
    @Override
    public ItemAlbum selectItemAlbumById(Long id) {
        return itemAlbumMapper.selectItemAlbumById(id);
    }

    /**
     * 查询项目专辑关系
     *
     * @param ids 项目专辑关系ID串
     * @return 项目专辑关系
     */
    public List<ItemAlbum> selectItemAlbumListByIds(String ids){
        return itemAlbumMapper.selectItemAlbumListByIds(Convert.toStrArray(ids));
    }

    /**
     * 查询项目专辑关系列表
     *
     * @param itemAlbum 项目专辑关系
     * @return 项目专辑关系
     */
    @Override
    public List<ItemAlbum> selectItemAlbumList(ItemAlbum itemAlbum) {
        return itemAlbumMapper.selectItemAlbumList(itemAlbum);
    }

    /**
     * 新增项目专辑关系
     *
     * @param itemAlbum 项目专辑关系
     * @return 结果
     */
    @Override
    public int insertItemAlbum(ItemAlbum itemAlbum) {
        itemAlbum.setCreateTime(DateUtils.getNowDate());
        return itemAlbumMapper.insertItemAlbum(itemAlbum);
    }

    /**
     * 修改项目专辑关系
     *
     * @param itemAlbumList 项目专辑集合
     * @param user 操作人
     * @param state 操作
     * @param operateReason 操作原因
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateItemAlbum(List<ItemAlbum> itemAlbumList, SysUser user, int state, String operateReason) throws Exception{
        ItemAlbumOperateLog ialog;
        Date nowDate = DateUtils.getNowDate();
        //发送邮件需要
        List<Album> albumList = new ArrayList<>();
        Album album;
        for (ItemAlbum itemAlbum : itemAlbumList){
            itemAlbum.setState(state);
            if (state == 11) {
                itemAlbum.setState(1);
            }
            if (state == 3) {
                itemAlbum.setOnlineTime(nowDate);
                //同步媒资列表专辑上线状态
                albumMapper.changeAlbumState(itemAlbum.getAlbumId(),1);
            } else if (state == 4) {
                itemAlbum.setOfflineTime(nowDate);
                //同步媒资列表专辑下线状态
                changeAlbumOnlineState(itemAlbum.getItemId(), itemAlbum.getAlbumId(), 0);
                //记录上线年份，月份，上线天数
                updateOnlineInfo(itemAlbum);
            } else if (state == 2) {
                itemAlbum.setOutstockTime(nowDate);
            }
            itemAlbum.setUpdateTime(nowDate);
            itemAlbum.setOperateReason(operateReason);
            itemAlbumMapper.updateItemAlbum(itemAlbum);
            ialog = new ItemAlbumOperateLog();
            ialog.setItemAlbumId(itemAlbum.getId());
            ialog.setOperateState(state);
            ialog.setOperateTime(nowDate);
            ialog.setOperateName(user.getUserName());
            ialog.setOperateReason(operateReason);
            itemAlbumOperateLogMapper.insertItemAlbumOperateLog(ialog);

            if (state == -1 || state == 3 || state == 4){
                album = new Album();
                album.setAlbumId(itemAlbum.getAlbumId());
                album.setTitle(itemAlbum.getTitle());
                album.setClassName(itemAlbum.getClassName());
                album.setAuthorizerName(itemAlbum.getAuthorizerName());
                albumList.add(album);
            }

        }
        //不可上线、上线、下线邮件通知
        if (albumList.size() > 0){
            sendOperateMail(state,itemAlbumList.get(0).getItemName(),operateReason,albumList);
        }
        return 1;
    }

    //更新专辑表状态 onlineState(0下线，1上线)
    private void changeAlbumOnlineState(Long itemId, Long albumId, int onlineState) {
        //此专辑在其他项目中上线个数
        int onlineCount = itemAlbumMapper.getOnlineCount(itemId, albumId);
        if (onlineCount == 0) {
            albumMapper.changeAlbumState(albumId, onlineState);
        }
    }

    //下线时设置上线年份，月份，上线天数
    private void updateOnlineInfo(ItemAlbum itemAlbum) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM");
        String beginDate = sdf.format(itemAlbum.getOnlineTime());
        String endDate = sdf.format(itemAlbum.getOfflineTime());
        StringBuilder sb = new StringBuilder((null == itemAlbum.getOnlineInfo() || "".equals(itemAlbum.getOnlineInfo()) ? "" : itemAlbum.getOnlineInfo() + ","));
        //每月上线的天数
        long days;
        try {
            //取得上线的月份集合，2020-04 这种的
            List<String> monthList = findMonthsStr(beginDate,endDate);
            int size = monthList.size();
            String firstMonth = monthList.get(0);
            if (size < 2){
                days = (sdf.parse(endDate).getTime() - sdf.parse(beginDate).getTime())/(60*60*24*1000);
                sb.append(firstMonth + "_" + days);
            }else {
                days = (sdf.parse(firstMonth + "-" + getDaysOfMonth(sdfMonth.parse(firstMonth))).getTime() - sdf.parse(beginDate).getTime())/(60*60*24*1000);
                sb.append(firstMonth + "_" + days + ",");
                for (int i = 1; i < size ; i++) {
                    if (i != size - 1){
                        days = getDaysOfMonth(sdfMonth.parse(monthList.get(i)));
                        sb.append(monthList.get(i) + "_" + days + ",");
                    }else {
                        days = (sdf.parse(endDate).getTime() - sdf.parse(monthList.get(i) + "-01").getTime())/(60*60*24*1000);
                        sb.append(monthList.get(i) + "_" + days);
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        itemAlbum.setOnlineInfo(sb.toString());
    }

    //获取两个指定日期之间的所有月份
    public static List<String> findMonthsStr(String beginTime, String endTime) throws ParseException {
        List<String> monthsStrList = new ArrayList<>();
        //格式化为年月 2020-01
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(beginTime));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(endTime));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        while (min.before(max)) {
            monthsStrList.add(sdf.format(min.getTime()));
            min.add(Calendar.MONTH, 1);
        }
        return monthsStrList;
    }

    //获取此月份总天数
    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }


    /**
     * 发送操作专辑邮件通知
     * @param state 操作类型
     * @param itemName 项目名称
     * @param albumList 片单列表（选用）
     * @return 结果
     */
    public void sendOperateMail(int state, String itemName, String notAllowOnlineReason, List<Album> albumList){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String now = sdf.format(date);
        String subject;
        String text;
        if (state == 4){
            subject = "下线确认" + "_" + itemName;
            text = "<h5>请注意：" +
                    "<br />\n" +
                    "以下内容于 [" + now + "] 时在[" + itemName + "]项目下线，请查收，多谢！" +
                    "<br />\n" +
                    "<br/>下线片单如下：\n</h5>";
            String jsonParam = MailInfoUtil.getRequestJsonParam(subject,text,MailInfoUtil.OFF_LINE,albumList);
            rabbitmqTemplate.convertAndSend(RabbitConstant.DIRECT_EMAIL_EXCHANGE,RabbitConstant.EMAIL_ROUTING,jsonParam);
        }else if (state == 3){
            subject = "上线确认" + "_" + itemName;
            text = "<h5>请注意：" +
                    "<br />\n" +
                    "以下内容于 [" + now + "] 时在[" + itemName + "]项目上线，请查收，多谢！" +
                    "<br />\n" +
                    "<br/>上线片单如下：\n</h5>";
            String jsonParam = MailInfoUtil.getRequestJsonParam(subject,text,MailInfoUtil.ON_LINE,albumList);
            rabbitmqTemplate.convertAndSend(RabbitConstant.DIRECT_EMAIL_EXCHANGE,RabbitConstant.EMAIL_ROUTING,jsonParam);
        }else if (state == -1){
            subject = "不可上线" + "_" +itemName;
            text = "<h5>请注意：" +
                    "<br />\n" +
                    "以下内容因 [" + notAllowOnlineReason + "] 在[" + itemName + "]项目不可上线，请了解，多谢！" +
                    "<br />\n" +
                    "<br/>不可上线片单如下：\n</h5>";
            String jsonParam = MailInfoUtil.getRequestJsonParam(subject,text,MailInfoUtil.NOT_ALLOW_ON_LINE,albumList);
            rabbitmqTemplate.convertAndSend(RabbitConstant.DIRECT_EMAIL_EXCHANGE,RabbitConstant.EMAIL_ROUTING,jsonParam);
        }
    }

    /**
     * 删除项目专辑关系对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteItemAlbumByIds(String ids) {
        return itemAlbumMapper.deleteItemAlbumByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除项目专辑关系信息
     *
     * @param id 项目专辑关系ID
     * @return 结果
     */
    public int deleteItemAlbumById(Long id) {
        return itemAlbumMapper.deleteItemAlbumById(id);
    }

    //结算
    public List<Settlement> getSettlementList(Settlement settlement) {
        List<Settlement> settlementList = null;
        StringBuilder sb = new StringBuilder("");
        String month = (String)settlement.getParams().get("month");
        if (month.length() == 6){
            month = month.substring(0,5) + "0" + month.substring(5);
        }
        String itemName = itemMapper.selectItemById(settlement.getItemId()).getName();
        List<ItemAlbum> list = itemAlbumMapper.getSettlementList(settlement.getItemId(),month);
        if (null != list && list.size() > 0){
            String onlineInfo;
            String[] monthDays;
            int days;
            for (ItemAlbum i : list){
                onlineInfo = i.getOnlineInfo();
                monthDays = onlineInfo.split(",");
                for (String monthDay : monthDays){
                    days = Integer.parseInt(monthDay.substring(8));
                    if (month.equals(monthDay.substring(0,7)) && days >= 15){
                        sb.append(i.getAlbumId() + ",");
                        break;
                    }
                }
            }
        }
        if (!"".equals(sb.toString())){
            String[] albumIds = sb.toString().split(",");
            settlementList = albumMapper.settlementList(albumIds,itemName);
        }
        if (null == settlementList || settlementList.size() == 0  ){
            settlementList = new ArrayList<>();
        }
        return settlementList;
    }
}
